<?PHP
	$userName = "root";
	$password = "group05";
	$database = "test";
	$server = "cg3002-05-z.comp.nus.edu.sg";
	$table = "admin";

	$conn = mysql_connect($host, $db_username, $db_password) 
		or die ('Error Cannot Connect to MySQL');

	@mysql_select_db($database) or die( "Unable to select database");

	if(isset($_FILES['datatxtfile']))
	{
		$allowedExts = array("txt", "csv");
		$extension = end(explode(".", $_FILES["datatxtfile"]["name"]));
		if(in_array($extension, $allowedExts))
		{
			if ($_FILES["datatxtfile"]["error"] > 0)
				echo "Error: " . $_FILES["datatxtfile"]["error"];
			else {
				echo "uploading";
				uploadTxtData($_FILES["datatxtfile"]["tmp_name"]);
			}
		}
		else
			echo "Invalid File";
	}
	else
	{
	}							

function uploadTxtData($filename)
{	
	$file = fopen( $filename, "r" ) or die ('ERROR: fopen()');
	
	$filesize = filesize( $filename );
	$filetext = fread( $file, $filesize );
	
	fclose( $file );
	$content = explode("\n", $filetext);
	foreach($content as $line)
	{
		list($adminID, $password, $shopID, $Name, $isHQAdmin) = explode(":",$line);
		//println($name);
		$query = "INSERT INTO admin()
					VALUES('".$adminID."', '".$password."', '".$shopID."',
							'".$Name."', '".$isHQAdmin."')";
		$result = mysql_query($query) or die(mysql_error());
	}	

	$query = "Select * From admin";
	$result = mysql_query($query);
	echo '<table class="table table-condensed table-hover table-bordered">';
	echo "<thead><th>Admin ID</th><th>Password</th><th>Shop ID</th><th>
	      Admin Name</th><th>isHQAdmin</th></tr></thead><tbody>";
	
	while($row = mysql_fetch_array($result)) 
	{
		echo "<tr>";
		echo "<td>".$row['adminID']."</td>";
		/*echo "<td>".$row['category']."</td>";
		echo "<td>".$row['manufacturer']."</td>";
		echo "<td>".$row['barcode']."</td>";
		echo "<td>".$row['costprice']."</td>";
		echo "<td>".$row['currentstock']."</td>";
		echo "<td>".$row['minstock']."</td>";
		echo "<td>".$row['bundleunit']."</td>";*/
		echo "</tr>";
	}
	
	echo "</table>";
}

function println($string_message = '') {
	return isset($_SERVER['SERVER_PROTOCOL']) ? print "$string_message<br />" . PHP_EOL:
		print $string_message . PHP_EOL;
}

function db_escape_string($text) {
	if (function_exists('mb_detect_encoding')) {
		$cur_encoding = mb_detect_encoding($text);
		if(($cur_encoding != "UTF-8" && $cur_encoding != "ASCII") || !mb_check_encoding($text, "UTF-8")) 
			$text = utf8_encode($text);
	}
	return mysql_escape_string($text);
}
?>